package com.xmler.plugin.adbrocket.adb.command

import com.android.ddmlib.IDevice
import com.intellij.openapi.project.Project
import com.xmler.plugin.adbrocket.shell.ShellFacade
import com.xmler.plugin.adbrocket.utils.Logger
import org.jetbrains.android.facet.AndroidFacet
import javax.swing.JTextArea

class UsbToWifiConnectCmd : ICommand {
    override fun run(project: Project, device: IDevice, facet: AndroidFacet, packageName: String, display: JTextArea): Boolean {
        var status = -1
        try {
            val ip = ShellFacade.getWlanIpAddr(project, device)
            Logger.d("The device's ip is $ip")
            Logger.d("Ready to connect ...")
            val shellReaderResult = ShellFacade.execute(project, device, "tcpip 5555")
            status = shellReaderResult.status
            Logger.d("adb connect $ip > $status")
            if (status == 0) {
                val connectResult = ShellFacade.execute(project, device, "connect $ip")
                status = connectResult.status
                Logger.d("adb connect $ip > $status")
                if (status == 0 ) {
                    val failed = connectResult.output.find {
                        it.contains("failed to connect")
                    }
                    if (failed.isNullOrEmpty()) {
                        Logger.d("connect success")
                        return true
                    }
                }
            }
        } catch (e: Exception) {
            Logger.e("UsbToWifiConnect error: $e")
        }
        Logger.d("connect failure: $status")
        return false
    }

}
